package com.tender.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * java 工具类，两个图片合并，图片入参类型是 BufferedImage，支持水平合并和垂直合并，默认垂直合并。
 */
public class ImageMergerUtil {

    /**
     * 合并两张图片，默认垂直合并。
     * @param img1 第一个图片
     * @param img2 第二个图片
     * @param isHorizontal 是否水平合并，默认垂直合并
     * @return 合并后的BufferedImage
     */
    public static BufferedImage mergeImages(BufferedImage img1, BufferedImage img2, boolean isHorizontal) {
        if (isHorizontal) {
            return mergeImagesHorizontally(img1, img2);
        } else {
            return mergeImagesVertically(img1, img2);
        }
    }

    // 水平合并两个图片
    private static BufferedImage mergeImagesHorizontally(BufferedImage img1, BufferedImage img2) {
        // 创建一个新的BufferedImage，宽度为两张图片宽度之和，高度为两张图片中较高的高度
        int width = img1.getWidth() + img2.getWidth();
        int height = Math.max(img1.getHeight(), img2.getHeight());

        BufferedImage mergedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics g = mergedImage.getGraphics();

        // 绘制第一个图片
        g.drawImage(img1, 0, 0, null);

        // 绘制第二个图片
        g.drawImage(img2, img1.getWidth(), 0, null);

        g.dispose(); // 释放图形上下文资源

        return mergedImage;
    }

    // 垂直合并两个图片
    private static BufferedImage mergeImagesVertically(BufferedImage img1, BufferedImage img2) {
        // 创建一个新的BufferedImage，宽度为两张图片中较宽的宽度，高度为两张图片高度之和
        int width = Math.max(img1.getWidth(), img2.getWidth());
        int height = img1.getHeight() + img2.getHeight();

        BufferedImage mergedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics g = mergedImage.getGraphics();

        // 绘制第一个图片
        g.drawImage(img1, 0, 0, null);

        // 绘制第二个图片
        g.drawImage(img2, 0, img1.getHeight(), null);

        g.dispose(); // 释放图形上下文资源

        return mergedImage;
    }

    public static void main(String[] args) {
        try {
            // 读取两张图片
            BufferedImage img1 = ImageIO.read(new File("image1.png"));
            BufferedImage img2 = ImageIO.read(new File("image2.png"));

            // 默认垂直合并
            BufferedImage verticalMerge = ImageMergerUtil.mergeImages(img1, img2, false);
            ImageIO.write(verticalMerge, "PNG", new File("vertical_merged.png"));

            // 水平合并
            BufferedImage horizontalMerge = ImageMergerUtil.mergeImages(img1, img2, true);
            ImageIO.write(horizontalMerge, "PNG", new File("horizontal_merged.png"));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
